<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * A generic controller superclass from which all other controllers inherit.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
abstract class DMAbstractController {

	/** number of seconds to sleep() during authentication */
	const AUTHENTICATION_DELAY = 4;

	/** @var DMAbstractForm */
	private $form;
	/** @var DMTemplateSet */
	private $template_set;

	protected function authorize() {
		if (!$this->getUser()) {
			DMHTTPRequest::redirectToParams("objects/login");
			die;
		}
	}

	/**
	 * @return DMAbstractForm
	 */
	protected function getForm() {
		return $this->form;
	}

	/**
	 * @param DMAbstractForm form
	 */
	protected function setForm(DMAbstractForm $form) {
		$this->form = $form;
	}

	/**
	 * @return DMTemplateSet
	 */
	protected final function getHTTPRequest() {
		return DMHTTPRequest::getCurrent();
	}

	/**
	 * @return DMTemplateSet
	 */
	protected final function getTemplateSet() {
		return $this->template_set;
	}

	/**
	 * @param DMTemplateSet set
	 */
	public final function setTemplateSet(DMTemplateSet $set) {
		$this->template_set = $set;
	}

	/**
	 * @param string flash_msg Override the default flash message
	 * @param string dest_params Redirect to the given params upon success
	 */
	protected function handleForm($flash_msg = null, $dest_params = null) {
		try {
			$this->getForm()->validate();
			$this->getForm()->doAction();
			$flash_msg = ($flash_msg)
				? $flash_msg : DMLocalizedString::getString("PREFS_UPDATED");
			$this->getSession()->setFlash(
					new DMFlash($flash_msg, true));
			if ($dest_params) {
				DMHTTPRequest::redirectToParams($dest_params);
			} else {
				DMHTTPRequest::reload();
			}
			die;
		} catch (Exception $e) {
			$flash_msg = $e->getMessage();
		}
		$this->getSession()->setFlash(
				new DMFlash($flash_msg, false));
	}

	/**
	 * @return DMSession
	 */
	protected final function getSession() {
		return $this->getHTTPRequest()->getSession();
	}

	/**
	 * @return DMUser
	 */
	protected final function getUser() {
		return $this->getSession()->getUser();
	}

}
